//
//  YAYIPerformanceLineChart.m
//  YAYIDoctor
//
//  Created by Veer on 16/5/10.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "YAYIPerformanceLineChart.h"

#define bottomMargin 20.0
#define topMargin 0
#define leftMargin 20

#define pointGrayColor YAYIColor(170, 170, 170)
#define lineGrayColor YAYIColor(215, 215, 215)
#define lineGreenColor YAYIColor(114, 150, 52)



@implementation YAYIPerformanceModel


-(void)setValue:(id)value forUndefinedKey:(NSString *)key
{
}

@end


@implementation YAYIPerformanceLineChart

@synthesize dataArray = _dataArray;

- (void)setDataArray:(NSMutableArray *)dataArray
{
    _dataArray = dataArray;
    [self setNeedsDisplay];
}

- (NSMutableArray *)dataArray
{
    if (nil == _dataArray) {
        _dataArray = [NSMutableArray array];

//        NSInteger startTimeStamp = [self getTimeStampBy:@"07:00"];

        // 模拟数据
//        YAYIPerformanceModel *model0 = [[YAYIPerformanceModel alloc] init];
//        model0.timeStamp = startTimeStamp + 60 * 60;
//        model0.performance = 800;
//        [_dataArray addObject:model0];
//        
//        YAYIPerformanceModel *model1 = [[YAYIPerformanceModel alloc] init];
//        model1.timeStamp = startTimeStamp + 4 * 60 * 60;
//        model1.performance = 500;
//        [_dataArray addObject:model1];
    }
    return _dataArray;
}

- (NSArray *)xArray
{
    if (nil == _xArray) {
//        _xArray = @[@"07:00", @"09:00", @"11:00", @"13:00", @"15:00", @"17:00", @"19:00"];
    }
    return  _xArray;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        
        self.backgroundColor = [UIColor whiteColor];

    }
    return self;
}


- (void)drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // 画x，y轴
    [YAYIColor(114, 150, 52) set];
    CGContextSetLineWidth(ctx, 1.2);
    
    CGContextMoveToPoint(ctx, 0, self.height - bottomMargin);
    CGContextAddLineToPoint(ctx, self.width, self.height - bottomMargin);
    
    CGContextMoveToPoint(ctx, 20, 0);
    CGContextAddLineToPoint(ctx, 20, self.height - bottomMargin);
    CGContextStrokePath(ctx);
    
    // 画中间的线
    [YAYIColor(215, 215, 215) set];
    CGContextSetLineWidth(ctx, 1.0);
    CGFloat lineMargin = (self.width - 2 * leftMargin) / (self.xArray.count - 1);
    
    CGFloat startX = leftMargin;
    CGFloat startY = self.height - bottomMargin;
    CGFloat endY = 0;
    
    for (int i = 1; i < self.xArray.count; i++) {
        
        if (1 == i || self.xArray.count - 1 == i) {

            UILabel *xLbl = [[UILabel alloc] init];
            xLbl.font = [UIFont systemFontOfSize:12];
            xLbl.textColor = YAYIColor(145, 149, 154);
            [self addSubview:xLbl];
            
            if (i == 1) {
                xLbl.text = self.xArray[0];
                [xLbl mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(@(startY));
                    make.centerX.mas_equalTo(self.mas_left).offset(20);
                    make.height.equalTo(@20);
                }];
            }else{
                xLbl.text = [self.xArray lastObject];
                [xLbl mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(@(startY));
                    make.centerX.mas_equalTo(self.mas_right).offset(-20);
                    make.height.equalTo(@20);
                }];
            }
        }
        
        startX += lineMargin;
        
        
        CGContextMoveToPoint(ctx, startX, startY);
        CGContextAddLineToPoint(ctx, startX, endY);
    }
    
    CGContextStrokePath(ctx);
    
    // 求出最大xy值
    NSInteger minX = [self getTimeStampBy:@"07:00"];
    NSInteger maxX = 12 * 60 * 60;
    
    
    // 判断折线图类型，获取x起点和x轴长度
    if (ChartTypeThisMonth == self.chartType) { // 本月
        minX = [self getStartStampInMonth];
        maxX = 24 * 60 * 60 * ([self getNumberOfDaysInMonth] - 1);
    }else if (ChartTypeThisYear == self.chartType){ // 今年
        minX = [self getStartStampInYear];
        maxX = 24 * 60 * 60 * ([self getNumberOfDaysInYear] - 31);
    }else{ // 今天
        minX = [self getTimeStampBy:@"07:00"];
        maxX = 12 * 60 * 60;
    }
    
    CGFloat maxY = 0.0;
    for (YAYIPerformanceModel *model in self.dataArray) {
        NSInteger data = (DataTypeServiceCount == self.dataType) ? model.servieNum : model.totalprice;
        if (data > maxY) {
            maxY = data;
        }
    }
    maxY = maxY == 0 ? 1.5 : maxY * 1.5;
    
    // 画线
    NSMutableArray *pointArray = [NSMutableArray array];
    
    if (DataTypeServiceCount == self.dataType) {
        [lineBlueColor set];
    }else{
        [lineOrangeColor set];
    }
    
    
    CGFloat prePointX = 0;
    CGFloat prePointY = 0;
    for (int i = 0; i < self.dataArray.count; i++) {
        YAYIPerformanceModel *model = self.dataArray[i];
        NSInteger data = (DataTypeServiceCount == self.dataType) ? model.servieNum : model.totalprice;
        // 计算点坐标
        CGFloat scaleX = (model.starttime - minX) / (maxX * 1.0);
        CGFloat ponintX = scaleX * (self.width - 2 * leftMargin) + leftMargin;
        CGFloat ponintY = self.height - bottomMargin - data / (maxY * 1.0) * (self.height - bottomMargin);
        
        // 保存点坐标
        CGPoint point = CGPointMake(ponintX, ponintY);
        [pointArray addObject:[NSValue valueWithCGPoint:point]];
        
        
        // 画线
        if (prePointX != 0 || prePointY != 0) {
            CGContextAddLineToPoint(ctx, ponintX, ponintY);
        }
        
        CGContextMoveToPoint(ctx, ponintX, ponintY);
        
        prePointX = ponintX;
        prePointY = ponintY;
    }
    CGContextStrokePath(ctx);
    
    // 画点及Label
    [pointGrayColor set];
    CGPoint prePoint = CGPointMake(self.width - leftMargin, self.height - bottomMargin);
    for (int i = 0; i < pointArray.count; i++) {
        CGPoint point = [pointArray[i] CGPointValue];
        
        YAYIPerformanceModel *model = self.dataArray[i];
        
        UILabel *performanceLbl = [[UILabel alloc] init];
        
        if (DataTypeServiceCount == self.dataType) {
            performanceLbl.text = [NSString stringWithFormat:@"%ld", model.servieNum];
        }else{
            performanceLbl.text = [NSString stringWithFormat:@"%.2f", model.totalprice / 100.0];
        }
//        performanceLbl.text = [NSString stringWithFormat:@"%ld", (DataTypeServiceCount == self.dataType) ? model.servieNum : model.totalprice];
        performanceLbl.backgroundColor = (DataTypeServiceCount == self.dataType) ?  lineBlueColor : lineOrangeColor;
        performanceLbl.textColor = [UIColor whiteColor];
        performanceLbl.font = [UIFont systemFontOfSize:13];
        performanceLbl.textAlignment = NSTextAlignmentCenter;
        performanceLbl.layer.masksToBounds = YES;
        performanceLbl.layer.cornerRadius = 3.0;
        [self addSubview:performanceLbl];
        
        // 1表示在上方显示， -1下方显示， 用于判断当线水平时候显示位置
        int preLevelFlag = 0;
        // 判断文字在点上面还是下面显示
        if (point.y > prePoint.y || (point.y == prePoint.y && preLevelFlag > 0)) { // 在点下方
            preLevelFlag = -1;
            [performanceLbl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self.mas_left).offset(point.x);
                make.width.greaterThanOrEqualTo(@30);
                make.top.equalTo(self.mas_top).offset(point.y + 5);
                
            }];
        }else if (point.y < prePoint.y  || (point.y == prePoint.y && preLevelFlag <= 0)){
            preLevelFlag = 1;
            [performanceLbl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self.mas_left).offset(point.x);
                make.width.greaterThanOrEqualTo(@30);
                make.bottom.equalTo(self.mas_top).offset(point.y - 5);
                
            }];
        }else{ // 水平
            
        }
        
        CGContextMoveToPoint(ctx, point.x, point.y);
        CGContextAddArc(ctx, point.x, point.y, 3.0, -M_PI_2, M_PI_2 * 3, 0);
        CGContextClosePath(ctx);
        
        prePoint = point;
    }
    
    
//    CGContextStrokePath(ctx);
    CGContextFillPath(ctx);
}

#pragma mark - 工具方法
/** 通过时间获取时间戳 */
- (NSInteger)getTimeStampBy:(NSString *)timeStr
{
    NSDate *nowDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = [NSString stringWithFormat:@"YYYY-MM-dd %@", timeStr];
    NSString *dateStr = [dateFormatter stringFromDate:nowDate];
    
    dateFormatter.dateFormat = @"YYYY-MM-dd hh:mm";
    NSDate *lastDate = [dateFormatter dateFromString:dateStr];
    
    
    NSInteger timeStamp = [lastDate timeIntervalSince1970];
    return timeStamp;
}

/** 获取本月的天数 */
- (NSInteger)getNumberOfDaysInMonth
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:[NSDate date]];
    NSUInteger numberOfDaysInMonth = range.length;
    
    return numberOfDaysInMonth;
}

/** 获取本年的天数 */
- (NSInteger)getNumberOfDaysInYear
{
    NSUInteger days = 0;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *today = [NSDate date];
    NSDateComponents *components = [calendar components:NSYearCalendarUnit fromDate:today];

    for (int i = 1; i <= 12; i++) {
        components.month = i;
        NSDate *month = [calendar dateFromComponents:components];
        days += [calendar rangeOfUnit:NSDayCalendarUnit
                               inUnit:NSMonthCalendarUnit
                              forDate:month].length;
    }
    
    return days;
}

/** 获取本月的开始时间戳 */
- (NSInteger)getStartStampInMonth
{
    NSDate *curDate = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"YYYY-MM-01";
    NSString *dateStr = [formatter stringFromDate:curDate];
    
    formatter.dateFormat = @"YYYY-MM-dd";
    NSDate *startDate = [formatter dateFromString:dateStr];
    NSInteger startStamp = [startDate timeIntervalSince1970];
    
    return startStamp;
}


/** 获取本年的开始时间戳 */
- (NSInteger)getStartStampInYear
{
    NSDate *curDate = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"YYYY-01-01";
    NSString *dateStr = [formatter stringFromDate:curDate];
    
    formatter.dateFormat = @"YYYY-MM-dd";
    NSDate *startDate = [formatter dateFromString:dateStr];
    NSInteger startStamp = [startDate timeIntervalSince1970];
    
    return startStamp;
}

@end
